<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>111</div>
    <script>
      document.getElementsByTagName("div")[0].onclick = debounce(
        click,
        1000,
        true
      );
      function click() {
        console.log(this);
      }
      //triggleNow true 第一次也防抖 false第二次才防抖
      function debounce(fn, time, triggleNow) {
        let t = null;
        return function () {
          if (t) {
            clearTimeout(t);
            //这里只是关闭了定时器 但t还是定时器的id
            //只有t=null时才可以
          }
          if (triggleNow) {
            let exec = !t;

            t = setTimeout(function () {
              t = null;
            }, time);

            if (exec) {
              fn.apply(this, arguments);
            }
          } else {
            t = setTimeout(() => {
              fn.apply(this, arguments);
            }, time);
          }
        };
      }
    </script>
  </body>
</html>
